//
//  YWVedioView.m
//  Chinese
//
//  Created by yellow on 2019/6/4.
//  Copyright © 2019 YSLC. All rights reserved.
//

#import "YWVedioView.h"

@interface YWVedioView ()

// 播放器的Layer
@property (weak, nonatomic) AVPlayerLayer *playerLayer;

@property (weak, nonatomic) IBOutlet UIView *bgView;

@property(nonatomic,assign)BOOL isTag;

@end

@implementation YWVedioView


#warning - 当做到动态列表播放时候再参考投资快报看却了什么方法

// 快速创建View的方法
+ (instancetype)videoView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"YWVedioView" owner:nil options:nil] firstObject];
}

//懒加载player播放器
- (AVPlayer *)player
{
    if (!_player) {
        
        // 初始化Player和Layer
        _player = [[AVPlayer alloc] init];
    }
    return _player;
}

#pragma mark - 重新布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //将播放器涂层重新布局
    self.playerLayer.frame = self.bounds;
}


//1、一开始／刚创建后要做的事
- (void)awakeFromNib
{
    [super awakeFromNib];
    
    //创建播放器的涂层
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    //把涂层添加到imageView上
    [self.bgView.layer addSublayer:self.playerLayer];
    
    
//单击手势控制产生代理让控制器决定做什么，例如发布的回看是显示隐藏navBar，动态列表的是播放与暂停
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.bgView addGestureRecognizer:tap];
    
}



//2、重置URL／准备播放前要做的事
#pragma mark - 设置播放的视频
- (void)setVedioUrl:(NSURL *)vedioUrl
{
    _vedioUrl = vedioUrl;
    
    //把之前监听状态的监听者去掉
    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
        [self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        
    }
    
    //创建一个新的播放源item
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:vedioUrl];
    
    //现在播放的item
    self.currentItem = item;
    
    //用新的代替旧的
    [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
    
    //添加播放状态监听者
    [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_currentItem];
    
    //先隐藏播放器，因为播放器在imageView上面，所以隐藏imageView
//    self.bgView.hidden = YES;
    
    
}


//3、监听播放／开始播放后要做的事
#pragma mark - 观察者对应的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    AVPlayerItem *playerItem = object;
    
    //监听播放状态做出的响应
    if ([keyPath isEqualToString:@"status"]) {
        
        AVPlayerItemStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        
        if (status == AVPlayerItemStatusReadyToPlay) { //播放成功
            
            //准备播放的时候把bgView显示出来
//            self.bgView.hidden = NO;
            
            NSTimeInterval totalTime = CMTimeGetSeconds(playerItem.duration);
            
            
        } else { //播放失败
            
            YWLog(@"播放失败，可显示播放源不存在等等");
            
        }
    }
    
    //监听缓冲时间
    else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        
        NSArray *array = playerItem.loadedTimeRanges;
        
        //本次缓冲时间范围
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
        
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
//        YWLog(@"共缓冲：%.2f",totalBuffer);
//        
//        YWLog(@"缓冲进度在slider显示图片暂时做不了，要自定义slider")
        
    }
    
}



//4、播放完毕监听／播放完毕后要做的事
//播放完毕通知所做的方法
- (void)moviePlayDidEnd:(NSNotification *)notification {
    
    __weak typeof(self) weakSelf = self;
    
    //播放器回到最初位置
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        
    //重新播放
        [weakSelf.player play];
    }];
}

#warning - 单击手势控制产生代理让控制器决定做什么，例如发布的回看是显示隐藏navBar，动态列表的是播放与暂停
// 5、这里叫代理决定要做什么操作
- (void)tapAction:(UITapGestureRecognizer *)sender {
    
    self.isTag = !self.isTag;
    
    if ([self.delegate respondsToSelector:@selector(vedioView:didTapWithTag:)]) {
        [self.delegate vedioView:self didTapWithTag:self.isTag];
    }
}

#warning - 动态列表的播放这里可以有播放按钮的隐藏和显示
-(void)continueToPlay{
    
    [self.player play];
    
}

-(void)pause{
    
    [self.player pause];
    
}


//6、移除监听
- (void)dealloc
{
    [self.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    
    [self.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
